import Koa from "koa";
import cors from "koa2-cors";

import allRoutes from "./controller/routers";
import logger from "./utils/logger4js";

const app = new Koa();

//config cors
app.use(
  cors({
    origin: "http://localhost:4200",
    exposeHeaders: ["WWW-Authenticate", "Server-Authorization"],
    maxAge: 5,
    credentials: true,
    allowMethods: ["GET", "PUT", "POST", "PATCH", "DELETE", "HEAD", "OPTIONS"],
    allowHeaders: ["Content-Type", "Authorization", "Accept"]
  })
);

//error handler
app.use(async (ctx, next) => {
  try {
    await next();
    ctx.body = {code: 200, data: ctx.body};
  }catch(err) {
    logger.error(err);
    ctx.status = err.status || 500;
    ctx.body = {code: 500, "msg": "server error!!"};
  }
});
//routes
app.use(allRoutes);
app.use(async ctx => {
  ctx.response.set("Content-Type", "application/json");
});


app.listen(3000);
logger.debug("Koa server listening on port 3000");

export default app;
